/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

/*
 * Created on 25/04/2004
 */

package au.com.lastweekend.jim.io.jpeg;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import au.com.lastweekend.jim.io.jpeg.write.DefaultDirectoryWriterRegistry;
import au.com.lastweekend.jim.io.jpeg.write.JpegDirectoryWriter;
import au.com.lastweekend.jim.io.jpeg.write.JpegDirectoryWriterRegistry;
import au.com.lastweekend.jim.io.metadata.Directory;
import au.com.lastweekend.jim.io.metadata.Metadata;

/**
 * Write Jpeg files from metadata. Unless you really know what you are doing, you'll want to only write metadata objects that have
 * been read with {@link JpegReader}
 * 
 * @version $Id: JpegWriter.java,v 1.2 2005/06/09 11:15:36 ggardner Exp $
 * @author <a href="mailto:grant@lastweekend.com.au"> <Grant Gardner> </a>
 */
public class JpegWriter {

    private static final JpegDirectoryWriterRegistry DEFAULT_REGISTRY = new DefaultDirectoryWriterRegistry();
    private final JpegDirectoryWriterRegistry _registry;

    /**
     * Creates a JpegWriter that will perform no transformation of the image.
     * 
     */
    public JpegWriter() {

        this(DEFAULT_REGISTRY);
    }

    /**
     * Creates a JpegWriter with the requested registry, which can provide for image transformations
     * 
     * @param registry
     */
    public JpegWriter(JpegDirectoryWriterRegistry registry) {

        _registry = registry;
    }

    /**
     * Write metadata containing Image to a file according to the transformations of this writer. Note that no transformation on
     * the metadata itself will be done.
     * 
     * @param metadata
     *            Must contain a JpegImageDataDirectory and appropriate RawSegmentDirectories containing encoding information.
     * @param file
     * @throws JpegProcessingException
     */
    public void writeImage(Metadata metadata, File file) throws JpegProcessingException {

        OutputStream outStream = getBufferedOutputStream(file);
        writeImage(metadata, outStream);
        closeStream(outStream);

    }

    /**
     * Write image to the supplied output stream.
     * 
     * @param metadata
     *            Must contain a JpegImageDataDirectory and appropriate RawSegmentDirectories containing encoding information.
     * 
     * @param output
     * @throws JpegProcessingException
     */
    public void writeImage(Metadata metadata, OutputStream output) throws JpegProcessingException {

        writeJpegHeader(output);
        writeDirectories(metadata, output);
        writeEndOfImage(output);
    }

    private void writeJpegHeader(OutputStream output) throws JpegProcessingException {

        byte[] headerBytes = new byte[2];
        headerBytes[0] = (byte) 0xFF;
        headerBytes[1] = (byte) 0xD8;
        try {
            output.write(headerBytes);
        } catch (IOException e) {
            throw new JpegProcessingException(e);
        }

    }

    public void writeDirectories(Metadata metadata, OutputStream output) throws JpegProcessingException {

        Iterator<Directory> directoryIterator = metadata.getDirectoryIterator();
        while (directoryIterator.hasNext()) {
            Directory directory = directoryIterator.next();
            JpegDirectoryWriter segmentWriter = _registry.getDirectoryWriter(directory);
            if (segmentWriter != null) {
                segmentWriter.writeDirectory(directory, output);
            }
        }
    }

    private void writeEndOfImage(OutputStream output) throws JpegProcessingException {

        try {
            output.write(JpegSegment.SEGMENT_BOUNDARY);
            output.write(JpegSegment.MARKER_EOI);
        } catch (IOException e) {
            throw new JpegProcessingException("Error writing end of image", e);
        }
    }

    private BufferedOutputStream getBufferedOutputStream(File jpegFile) throws JpegProcessingException {

        try {
            OutputStream outStream = new FileOutputStream(jpegFile);
            return new BufferedOutputStream(outStream);
        } catch (FileNotFoundException e) {
            throw new JpegProcessingException(e);
        }

    }

    /**
     * @param outStream
     * @throws JpegProcessingException
     */
    private void closeStream(OutputStream outStream) throws JpegProcessingException {

        try {
            outStream.close();
        } catch (IOException e) {
            throw new JpegProcessingException("Error closing output stream", e);
        }

    }
}